package thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author weim
 * @date 18-8-29
 */
public class MyWait01 {

    private static Lock lock = new ReentrantLock();

    private static Condition condition = lock.newCondition();

    private static Integer index = 1;

    public static void main(String[] args) {

        for(int i=0; i<100; i++) {

            new Thread(() -> {

                sub("subOne");

            }).start();

            new Thread(() -> {

                sub("subTwo");

            }).start();

            new Thread(() -> {

                sub("subThree");

            }).start();

            new Thread(() -> {

                count("countOne");

            }).start();

            new Thread(() -> {

                count("countTwo");

            }).start();

        }

    }

    private static void count(String name) {

        lock.lock();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if(index > 10) {
            try {
                condition.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

//        condition.signal();
        condition.signalAll();

        index ++;
        System.out.println(name + " count>  " + index);

        lock.unlock();
    }

    private static void sub(String name) {

        lock.lock();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if(index <= 0) {
            try {
                condition.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        condition.signalAll();
        index--;
        System.out.println(name + " sub>  " + index);

        lock.unlock();

    }

}

